/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.supplierapply.service.impl.SupplierApplyServiceImpl
   Module Description   :

   Date Created      : 2009/12/3
   Original Author   : andy.chuang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.supplierapply.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.admin.entity.Role;
import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.admin.service.UserService;
import com.yaodian100.core.common.dao.ObjectDao;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.common.EnvParameters;
import com.yaodian100.ec.supplierapply.entity.NewSupplierApply;
import com.yaodian100.ec.supplierapply.entity.SupplierApply;
import com.yaodian100.ec.supplierapply.entity.SupplierApplyPhoto;
import com.yaodian100.ec.supplierapply.service.NewSupplierApplyService;
import com.yaodian100.ec.supplierapply.service.SupplierApplyService;

/**
 * @author Tina.xu
 * 
 */
public class NewSupplierApplyServiceImpl extends DomainServiceImpl<NewSupplierApply> implements NewSupplierApplyService {

	@Resource(name = "userService")
	private UserService userService;
	@Autowired
	private MailService mailService;
	@Autowired
	private TemplateService velocityService;
	@Autowired
	private EnvParameters envParameters;
	@Resource
	private SupplierApplyService supplierApplyService;
	@Resource(name = "supplierApplyPhotoDao")
	private ObjectDao<SupplierApplyPhoto> sapdao;

	@Override
	@Transactional(readOnly = false)
	public NewSupplierApply save(NewSupplierApply nsa) throws CoreException {
		if (nsa.getSupplierID() == null) {
			sendMail(nsa);
			nsa.setStatus(0);
		}
		nsa = super.save(nsa);
		return nsa;
	}

	private void sendMail(NewSupplierApply nsa) {
		// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Map<String, Object> contentMap = new HashMap<String, Object>();
		contentMap.put("nsa", nsa);
		List<User> users = userService.getByGroup("A-30-300-000");
		Mail mail = velocityService.formatToMail("supplier_apply_status_0", contentMap);
		mail.setFrom(envParameters.getEmailFromSystem());
		for (User u : users) {
			mail.addTo(u.getUsername(), u.getEmail());
		}
		mailService.save(mail);
	}

	@Override
	@Transactional(readOnly = false)
	public void approve1(NewSupplierApply nsa) {
		// TODO Auto-generated method stub
		nsa.setStatus(1);
		update(nsa);
		Map<String, Object> contentMap = new HashMap<String, Object>();
		contentMap.put("nsa", nsa);
		List<User> users = userService.getByRole(nsa.getCategory(), Role.Type.CATEGORY);
		if (users != null) {
			Mail mail = velocityService.formatToMail("supplier_apply_status_1", contentMap);
			mail.setFrom(envParameters.getEmailFromSystem());
			for (User u : users) {
				mail.addTo(u.getUsername(), u.getEmail());
			}
			mailService.save(mail);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void approve2(NewSupplierApply nsa) {
		// TODO Auto-generated method stub
		nsa.setStatus(2);
		update(nsa);
		SupplierApply sa = new SupplierApply();
		BeanUtils.copyProperties(nsa, sa, new String[] { "createUser", "createDate", "modifyUser", "modifyDate",
				"supplierID", "approveBy", "status", "category" });
		sa.setStatus(1);
		sa.setApproveStatus(0);
		supplierApplyService.saveOrUpdate(sa);
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteforPhoto(String photoId) throws CoreException {
		SupplierApplyPhoto sap = sapdao.get(photoId);
		File file = new File("/yaodian100.com/share/newsupplierapply/" + sap.getSupplierid() + "/" + sap.getFilename());
		try {
			file.delete();
		} catch (Exception e) {
			throw new CoreException("图片删除失败", e);
		}
		sapdao.deleteByPK(photoId);
	}

	@Override
	public List<SupplierApplyPhoto> getPhotos(String sphentityId) {
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("supplierid", sphentityId);
		return sapdao.getList(criteria, new String[] { "filedecription", "photoid" });
	}

	@Override
	@Transactional(readOnly = false)
	public SupplierApplyPhoto saveforPhoto(NewSupplierApply nsa, byte[] file, String decription, String imageFileName)
			throws CoreException {

		File folder = new File("/yaodian100.com/share/newsupplierapply/" + nsa.getSupplierID() + "/");
		if (!folder.exists()) {
			folder.mkdirs();
		}
		File checkfile = new File("/yaodian100.com/share/newsupplierapply/" + nsa.getSupplierID() + "/" + imageFileName);

		if (checkfile.exists()) {
			throw new CoreException("档案名称重复");
		}

		try {
			FileUtils.writeByteArrayToFile(checkfile, file);
		} catch (Exception e) {
			throw new CoreException("上传失败", e);
		}
		SupplierApplyPhoto sap = new SupplierApplyPhoto();
		sap.setFilename(imageFileName);
		sap.setSupplierid(nsa.getSupplierID());
		sap.setFiledecription(decription);

		return sapdao.save(sap);
	}

	@Override
	public SupplierApplyPhoto getPhoto(String photoId) {
		SupplierApplyPhoto entity = sapdao.get(photoId);
		return entity;
	}
}
